package com.coder.bike.security;

import com.coder.bike.entity.Customer;
import com.coder.bike.entity.Permission;
import com.coder.bike.entity.Staff;
import lombok.Builder;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Unified authentication user class combining Customer and Staff properties
 */
@Data
@Builder
public class AuthUser implements UserDetails {

    // Common fields from both entities
    private final Integer id;
    private final String username;
    private final String password;
    private final String nickname;
    private final boolean accountNonExpired;
    private final boolean accountNonLocked;
    private final boolean credentialsNonExpired;
    private final boolean enabled;
    private final String userType; // "STAFF" or "CUSTOMER"
    private final Collection<? extends GrantedAuthority> authorities;
    // Fields specific to Staff
    private final String realname;
    private final Integer deptId;
    private final String deptName;
    private final String gender;
    private final String phone;
    private final String email;
    private final String avatar;
    private final Boolean isAdmin;
    private final LocalDateTime createTime;
    private final LocalDateTime updateTime;
    private final boolean deleted;
    private final Integer createId;
    private List<Permission> permissionList;

    // Fields specific to Customer
    private final String name; // Customer's real name
    private final String tel;
    private final LocalDate birthday;
    private final String idNum;
    private final Boolean status;
    private final LocalDateTime lastRide;
    private final Boolean isVerified;
    private final String preferredType;
    private final String preferredBrand;
    private final Integer creditScore;

    /**
     * Create AuthUser from Staff entity
     */
    public static AuthUser fromStaff(Staff staff) {
        List<Permission> permissions = staff.getPermissionList();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        if (permissions != null) {
            authorities.addAll(permissions.stream()
                    .map(p -> new SimpleGrantedAuthority(p.getPermissionCode()))
                    .toList());
        }

        authorities.add(new SimpleGrantedAuthority("ROLE_STAFF"));
        if (staff.getIsAdmin() != null && staff.getIsAdmin()) {
            authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        }
        return AuthUser.builder()
                .id(staff.getId())
                .username(staff.getUsername())
                .password(staff.getPassword())
                .nickname(staff.getNickname())
                .accountNonExpired(staff.isAccountNonExpired())
                .accountNonLocked(staff.isAccountNonLocked())
                .credentialsNonExpired(staff.isCredentialsNonExpired())
                .enabled(staff.isEnabled())
                .userType("STAFF")
                .authorities(authorities)
                .realname(staff.getRealname())
                .deptId(staff.getDeptId())
                .deptName(staff.getDeptName())
                .gender(staff.getGender())
                .phone(staff.getPhone())
                .email(staff.getEmail())
                .avatar(staff.getAvatar())
                .isAdmin(staff.getIsAdmin())
                .createTime(staff.getCreateTime())
                .updateTime(staff.getUpdateTime())
                .deleted(staff.isDeleted())
                // Customer-specific fields set to null
                .name(null)
                .tel(null)
                .birthday(null)
                .idNum(null)
                .status(null)
                .lastRide(null)
                .isVerified(null)
                .preferredType(null)
                .preferredBrand(null)
                .creditScore(null)
                .permissionList(permissions)
                .authorities(authorities)
                .build();
    }

    public static AuthUser fromCustomer(Customer customer) {
        // 创建固定的权限菜单
        List<Permission> fixedPermissions = createFixedCustomerPermissions();

        return AuthUser.builder()
                .id(customer.getId())
                .username(customer.getUsername())
                .password(customer.getPassword())
                .nickname(customer.getNickname())
                .accountNonExpired(customer.isAccountNonExpired())
                .accountNonLocked(customer.isAccountNonLocked())
                .credentialsNonExpired(customer.isCredentialsNonExpired())
                .enabled(customer.isEnabled())
                .userType("CUSTOMER")
                .authorities(fixedPermissions.stream()
                        .map(p -> new SimpleGrantedAuthority(p.getPermissionCode()))
                        .collect(Collectors.toList()))
                .name(customer.getName())
                .tel(customer.getTel())
                .birthday(customer.getBirthday())
                .idNum(customer.getIdNum())
                .status(customer.getStatus())
                .lastRide(customer.getLastRide())
                .isVerified(customer.getIsVerified())
                .preferredType(customer.getPreferredType())
                .preferredBrand(customer.getPreferredBrand())
                .creditScore(customer.getCreditScore())
                // Staff-specific fields set to null
                .realname(null)
                .deptId(null)
                .deptName(null)
                .gender(null)
                .phone(null)
                .email(customer.getEmail())
                .avatar(customer.getAvatar())
                .isAdmin(null)
                .createTime(null)
                .updateTime(null)
                .authorities(fixedPermissions.stream()
                        .map(p -> new SimpleGrantedAuthority(p.getPermissionCode()))
                        .collect(Collectors.toList()))
                .deleted(customer.getDeleted() != null ? customer.getDeleted() : false)
                .permissionList(fixedPermissions)
                .build();
    }

    private static List<Permission> createFixedCustomerPermissions() {
        List<Permission> permissions = new ArrayList<>();
        Permission option = createPermission(
                1,
                "功能栏",
                0,
                "顶级菜单",
                "option:customer",
                "/option",
                "option",
                "/option/option",
                1,
                "guide",
                0
        );
        Permission service1= createPermission(
                2,
                "翔翔AI",
                1,
                "选项栏",
                "ai:xiangxiang",
                "/ai",  // 简化路径
                "xiangxiang",   // 组件名对应视图文件名
                "/option/ai/xiangxiang",  // 实际视图路径
                2,
                "guide",
                1
        );
        // 车辆服务菜单
        Permission service = createPermission(
                3,
                "车辆服务",
                1,
                "选项栏",
                "customer:service",
                "/service",  // 简化路径
                "service",   // 组件名对应视图文件名
                "/option/service/serviceList",  // 实际视图路径
                3,
                "el-icon-service",
                1
        );

        // 活动与福利菜单
        Permission activity = createPermission(
                4,
                "活动与福利", 1,
                "选项栏",
                "customer:activity",
                "/activity",  // 简化路径
                "activity",   // 组件名对应视图文件名
                "/option/activity/activityList",  // 实际视图路径
                4,
                "el-icon-present",
                1
        );
        permissions.add(option);
        permissions.add(service1);
        permissions.add(service);
        permissions.add(activity);

        return permissions;
    }

    private static Permission createPermission(int id, String label, int pid, String parentLabel,
                                               String code, String path, String name, String url,
                                               int orderNum, String icon, int permissionType) {
        Permission permission = new Permission();
        permission.setId(id);
        permission.setPermissionLabel(label);
        permission.setPid(pid);
        permission.setParentLabel(parentLabel);
        permission.setPermissionCode(code);
        permission.setRoutePath(path);
        permission.setRouteName(name);
        permission.setRouteUrl(url);
        permission.setOrderNum(orderNum);
        permission.setIcon(icon);
        permission.setPermissionType(permissionType); // 明确设置权限类型
        return permission;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}